import React, { useState, useEffect, useRef } from "react";
import { connect } from 'umi';
import { Radio, Row, Col, Button, Spin, Form, Card, Input, notification, Space } from 'antd';
import SelectTag from './components/SelectTag';
import SelectIntentionDirection from './components/SelectIntentionDirection';
import ExamYearCondition from "./components/examYearCondition";
import GoodsCondition from "./components/goodsCondition";
import SelectModel from '@/components/PackagingModel/components/SelectModel'
import StageCondition from "./components/stageCondition";
import IntentionDirectionCondition from "./components/intentionDirectionCondition";
import Tags from './components/Tags'
import TableDataBlock from '@/components/TableDataBlock';
import EditWhite from "./components/editWhite";
import PopImgShow from "@/components/PopImgShow";
import CopyToClipboard from 'react-copy-to-clipboard';
const SpecifyConditions = (props) => {
  const { detail = {}, dispatch, loading, list } = props
  const [tagVisible, setTagVisible] = useState(false);
  const [intentionDirectionVisible, setIntentionDirectionVisible] = useState(false);
  const [intentionCoursesVisible, setIntentionCoursesVisible] = useState(false);
  const [whiteVisible, setWhiteVisible] = useState(false)
  const [codevisible, codeSetVisible] = useState(false)
  const [stageList, setStageList] = useState([])
  const [plVisible, setPlvisible] = useState(false);
  const { id } = detail
  const [data, setData] = useState({
    authCode: '',
    examYearCondition: {
      conditionType: 'any',
      amount: 1
    },
    tagCondition: {
      conditionType: 'all',
    },
    goodsCondition: {
      conditionType: 'all',

    },
    stageCondition: {
      conditionType: 'any',
      amount: 1
    },
    intentionDirectionCondition: {
      conditionType: 'all',
    }
  })
  useEffect(() => {
    fetchStage()
  }, [])
  useEffect(() => {
    if (id) {
      fetchData()

    }

  }, [id])
  const { authCode, examYearCondition = {}, tagCondition = {}, goodsCondition = {}, stageCondition = {}, intentionDirectionCondition = {} } = data
  const updateSubmit = () => {
    let obj = {
      id: data.id || '',
      authCode
    }
    if (!examYearCondition.examYears) {
      obj.examYearCondition = ''
    }
    if (!stageCondition.stages) {
      obj.stageCondition = ''
    }
    if (!tagCondition.tabList || tagCondition.tabList.length === 0) {
      obj.tagCondition = ''
    }
    if (!goodsCondition.goods || goodsCondition.goods.length === 0) {
      obj.goodsCondition = ''
    }
    if (!intentionDirectionCondition.intentionDirections || intentionDirectionCondition.intentionDirections.length === 0) {
      obj.intentionDirectionCondition = ''
    }
    if (examYearCondition.examYears) {
      obj.examYearCondition = JSON.stringify(examYearCondition)
    }
    if (stageCondition.stages) {
      obj.stageCondition = JSON.stringify(stageCondition)
    }
    if (tagCondition.tabList && tagCondition.tabList.length > 0) {
      if (tagCondition.conditionType === 'all') {
        const { conditionType, amount, } = tagCondition
        obj.tagCondition = JSON.stringify({
          conditionType,
          amount,
          tagIds: tagCondition.tabList.map(item => { return item.id }).toString()
        })
      }
      else {
        if (tagCondition.conditionType === 'any' && !tagCondition.amount) {
          return notification.warning({
            message: '错误提示',
            description: `条件选择任意后，必须填写数量`,
          })
        }
        else {
          const { conditionType, amount, } = tagCondition
          obj.tagCondition = JSON.stringify({
            conditionType,
            amount,
            tagIds: tagCondition.tabList.map(item => { return item.id }).toString()
          })
        }
      }

    }
    if (goodsCondition.goods && goodsCondition.goods.length > 0) {
      if (goodsCondition.conditionType === 'all') {
        const { conditionType, amount, } = goodsCondition
        obj.goodsCondition = JSON.stringify({
          conditionType, amount,
          goodsIds: goodsCondition.goods.map(item => { return item.id }).toString()
        })
      }
      else {
        if (goodsCondition.conditionType === 'any' && !goodsCondition.amount) {
          return notification.warning({
            message: '错误提示',
            description: `条件选择任意后，必须填写数量`,
          })
        }
        else {
          const { conditionType, amount, } = goodsCondition
          obj.goodsCondition = JSON.stringify({
            conditionType, amount,
            goodsIds: goodsCondition.goods.map(item => { return item.id }).toString()
          })
        }
      }

    }
    if (intentionDirectionCondition.intentionDirections && intentionDirectionCondition.intentionDirections.length > 0) {
      const { conditionType, amount, } = intentionDirectionCondition
      if (intentionDirectionCondition.conditionType === 'all') {
        obj.intentionDirectionCondition = JSON.stringify({
          conditionType, amount,
          intentionDirectionIds: intentionDirectionCondition.intentionDirections.map(item => { return item.value }).toString()
        })
      }
      else {
        if (intentionDirectionCondition.conditionType === 'any' && !intentionDirectionCondition.amount) {
          return notification.warning({
            message: '错误提示',
            description: `条件选择任意后，必须填写数量`,
          })
        }
        else {
          const { conditionType, amount, } = intentionDirectionCondition
          obj.intentionDirectionCondition = JSON.stringify({
            conditionType, amount,
            intentionDirectionIds: intentionDirectionCondition.intentionDirections.map(item => { return item.value }).toString()
          })
        }
      }

    }
    dispatch({
      type: "liveStreaming/fakeGoodsAuth",
      payload: {
        ...obj,
        goodsId: id
      },
      callback: () => {
        fetchData()
      }
    })
  }
  const deleteSubmit = () => {
    dispatch({
      type: "liveStreaming/fakeDeleteGoodsAuth",
      payload: {
        goodsId: id,
        id: data.id
      },
      callback: () => {
        fetchData()
      }
    })
  }
  const fetchData = () => {
    dispatch({
      type: "liveStreaming/fetchGoodsAuth",
      payload: {
        goodsId: id
      },
      callback: (e = {}) => {
        if (e.goodsCondition) {
          const goodsData = JSON.parse(e.goodsCondition)
          const { goodsIds } = goodsData
          dispatch({
            type: 'liveStreaming/fetchGoodsByIds', payload: {
              goodsIds: goodsIds
            },
            callback: (val) => {
              setData({
                ...data,
                ...reloadData({
                  ...e,
                  goodsCondition: JSON.stringify({
                    ...goodsData,
                    goods: val
                  })
                })
              })
            }
          })

        }
        else {
          setData({
            ...data,
            ...reloadData(e)
          })
        }

      }
    })
  }
  const reloadData = (data) => {
    const { authCode } = data
    let obj = {}
    if (data.examYearCondition) {
      obj.examYearCondition = JSON.parse(data.examYearCondition)
    } if (data.stageCondition) {
      obj.stageCondition = JSON.parse(data.stageCondition)
    }
    if (data.goodsCondition) {
      const goodsData = JSON.parse(data.goodsCondition)
      const { goods, goodsIds } = goodsData
      if (goodsIds) {
        obj.goodsCondition = {
          ...goodsCondition,
          goods: goods
        }
      }
    }
    if (data.tagCondition) {
      const tagData = JSON.parse(data.tagCondition)
      const { tagIds, tagNames } = tagData
      let idList = tagIds.split(',')
      let nameList = tagNames.split(',')
      if (tagIds && tagNames) {
        obj.tagCondition = {
          ...tagData,
          tabList: idList.map((item, index) => {
            return {
              id: item,
              tagName: nameList[index]
            }
          })
        }
      }
    }

    if (data.intentionDirectionCondition) {
      const intentionData = JSON.parse(data.intentionDirectionCondition)
      const { intentionDirectionIds, intentionDirectionNames } = intentionData
      let idList = intentionDirectionIds.split(',')
      let nameList = intentionDirectionNames.split(',')
      if (intentionDirectionIds && intentionDirectionNames) {
        obj.intentionDirectionCondition = {
          ...intentionDirectionCondition,
          intentionDirections: idList.map((item, index) => {
            return {
              value: item,
              key: nameList[index]
            }
          })
        }
      }
    }
    return {
      id: data.id,
      authCode,
      ...obj
    }
  }
  const fetchStage = () => {
    dispatch({
      type: "selectionWindow/fetchListMainStageInfo",
      payload: {
        goodsId: id
      },
      callback: (e = {}) => {
        const { stageInfoList = [] } = e
        setStageList(stageInfoList.map(val => {
          const { stageInfo = {} } = val
          return {
            ...stageInfo,
            stage: val.stageIdentification
          }
        }))
        console.log(e)
      }
    })
  }
  const [selectedRow, setSelectedRow] = useState({
    selectedRowKeys: [],
    type: 'checked',
    preserveSelectedRowKeys: true,
    onChange: (val, selectedRows) => {
      setSelectedRow({
        ...selectedRow,
        selectedRowKeys: val,
      });
    },
  });
  const btnExtra = [
    {
      text: '新增白名单',
      onClick: () => {
        setWhiteVisible({
          show: true,
          detail: detail
        })
      },
    },
    {
      text: plVisible ? '取消批量移除' : '批量移除',

      typeBtn: 'primary',
      onClick: () => {
        setSelectedRow({
          ...selectedRow,
          selectedRowKeys: []
        })
        plVisible ? setPlvisible(null) : setPlvisible({ btnShow: true });
      },
    },
    {
      text: '批量移除白名单',
      typeBtn: 'default',
      show: plVisible,
      onClick: () => {
        if (selectedRow.selectedRowKeys.length === 0) {
          return notification.warn({
            message: '温馨提示',
            description: `请先选择要移除的号码`,
          });
        }
        deleteWhite(selectedRow.selectedRowKeys)
      },
    },
  ];
  const deleteWhite = (data) => {
    dispatch({
      type: 'liveStreaming/fakeDeleteGoodsWhitelist',
      payload: {
        goodsId: id,
        idList: data
      },
      callback: () => {
        handleCallback();
        setPlvisible(false)
        setSelectedRow({
          ...selectedRow,
          selectedRowKeys: []
        })
      }
    })
  }
  const searchItems = [
    { label: '关键词', name: 'keyword' },

  ];
  const childRef = useRef();
  const handleCallback = () => {
    childRef.current.fetchGetData();
  };
  const getColumns = [
    {
      title: '手机号码',
      dataIndex: 'mobile',
    },
    {
      title: '用户姓名',
      dataIndex: 'username',
    },
    {
      title: '头像',
      dataIndex: 'profile',
      render: (e) => {
        return <PopImgShow url={e}></PopImgShow>
      }
    },
  ];
  return <div>
    <Card title='设置指定观看码'>
      <Row>
        <Col span={8}>
          <Input
            onChange={(e) => {
              setData({
                ...data,
                authCode: e.target.value
              })
            }}
            disabled={!codevisible}
            value={authCode}>
          </Input>
        </Col>
        <Col offset={1}>
          <CopyToClipboard text={authCode} onCopy={() => {
            notification.success({
              message: '温馨提示',
              description: '复制成功',
            });
          }}>
            <Button type='link'>复制</Button>
          </CopyToClipboard>
          {codevisible ?
            <Button onClick={() => {
              codeSetVisible(() => {
                updateSubmit()
                return false
              })
            }} type='primary'>保存</Button>
            :
            <Button onClick={() => { codeSetVisible(true) }}>编辑</Button>
          }
        </Col>
      </Row>
    </Card>
    <Card extra={
      <Space>
        <Button type='primary' onClick={() => { updateSubmit() }}>保存</Button>
        <Button onClick={() => { deleteSubmit() }}>删除</Button>
      </Space>
    } title={'设置指定条件'}>
      <ExamYearCondition onChange={(e = {}) => {
        setData({
          ...data,
          examYearCondition: {
            ...examYearCondition,
            ...e,
          }
        })
      }} data={examYearCondition}></ExamYearCondition>
      <GoodsCondition
        setIntentionCoursesVisible={setIntentionCoursesVisible}
        onChange={(e = {}) => {
          setData({
            ...data,
            goodsCondition: {
              ...goodsCondition,
              ...e
            }
          })
        }} data={goodsCondition}></GoodsCondition>
      <StageCondition
        stageList={stageList}
        setIntentionCoursesVisible={setIntentionCoursesVisible}
        onChange={(e = {}) => {
          setData({
            ...data,
            stageCondition: {
              ...stageCondition,
              ...e
            }
          })
        }} data={stageCondition}></StageCondition>
      <IntentionDirectionCondition
        setIntentionDirectionVisible={setIntentionDirectionVisible}
        onChange={(e = {}) => {
          setData({
            ...data,
            intentionDirectionCondition: {
              ...intentionDirectionCondition,
              ...e
            }
          })
        }} data={intentionDirectionCondition}
      ></IntentionDirectionCondition>
      <Tags
        setTagVisible={setTagVisible}
        onChange={(e = {}) => {
          setData({
            ...data,
            tagCondition: {
              ...tagCondition,
              ...e
            }
          })
        }} data={tagCondition}
      ></Tags>
    </Card>
    <TableDataBlock
      rowSelection={plVisible ? selectedRow : false}
      cRef={childRef}
      cardProps={{ title: '白名单' }}
      // btnExtra={btnExtra}
      loading={loading}
      searchItems={searchItems}
      columns={getColumns}
      btnExtra={btnExtra}
      params={{
        goodsId: id
      }}
      rowKey={(record) => `${record.id}`}
      dispatchType="liveStreaming/fetchGoodsWhiteList"
      {...list}
    ></TableDataBlock>
    <SelectTag
      onSetList={(e) => {
        setData({
          ...data,
          tagCondition: {
            ...tagCondition,
            tabList: e
          }
        })
      }}
      visible={tagVisible}
      onClose={() => setTagVisible(false)}
    ></SelectTag>
    <SelectIntentionDirection
      onSetList={(e) => {
        setData({
          ...data,
          intentionDirectionCondition: {
            ...intentionDirectionCondition,
            intentionDirections: e
          }
        })

      }}
      visible={intentionDirectionVisible}
      onClose={() => setIntentionDirectionVisible(false)}
    ></SelectIntentionDirection>
    <SelectModel
      payType={true}
      hasSku={'0'} onOk={(e) => {
        const handeleList = (e) => {
          return Object.values(e).reduce((item, val) => {
            return [...item, ...val]
          }, [])
        }
        setData({
          ...data,
          goodsCondition: {
            ...goodsCondition,
            goods: handeleList(e)
          }
        })
      }} visible={intentionCoursesVisible} onClose={() => setIntentionCoursesVisible(false)}></SelectModel>
    <EditWhite handleCallback={handleCallback} visible={whiteVisible} onClose={() => setWhiteVisible(false)}></EditWhite>
  </div>
}
export default connect(({ liveStreaming, loading }) => ({
  list: liveStreaming.whitelistList,
  loading: loading.effects['liveStreaming/fetchGoodsAuth']
}))(SpecifyConditions);;
